<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-06-03 16:42:11
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2024-06-04 14:09:36
 * @FilePath: /consult-patient-vue3-ts/src/views/Room/index.vue
 * @Description: 
 * 
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
-->
<script setup lang="ts">
import RoomStatus from './components/RoomStatus.vue'
import RoomMessage from './components/RoomMessage.vue'
import RoomAction from './components/RoomAction.vue'
import type { Socket } from 'socket.io-client'
import { io } from 'socket.io-client'
import { onMounted, onUnmounted, ref, nextTick } from 'vue'
import { baseURL } from '@/utils/request'
import { useUserStore } from '@/stores'
import { useRoute } from 'vue-router'
import { MsgType } from '@/enums'
import type { Message, TimeMessages } from '@/types/room'
import type { ConsultOrderItem } from '@/types/consult'
import { getConsultOrderDetail } from '@/services/consult'
import { OrderType } from '@/enums'
import dayjs from "dayjs"
import { Toast } from 'vant'

const store = useUserStore()
const route = useRoute()

let socket: Socket
onUnmounted(() => {
  socket.close()//断线
})
// 获取聊天记录 start
const list = ref<Message[]>([])
onMounted(() => {
  //初始化socket
  socket = io(baseURL, {
    auth: { token: `Bearer ${store.user?.token}` },
    query: {
      orderId: route.query.orderId
    }
  })
  //监听连接
  socket.on('connect', () => {
    list.value = []
    console.log('socket连接成功');
  })
  //连接异常
  socket.on('error', (error) => {
    console.log(error + 'socket连接异常');
  })
  //断开连接
  socket.on('disconnect', () => {
    console.log('socket断开连接');
  })
  //1.监听聊天记录事件
  const initialMsg = ref(true)
  socket.on('chatMsgList', async ({ data }: { data: TimeMessages[] }) => {
    // 准备转换常规消息列表
    const arr: Message[] = []
    data.forEach((item, i) => {
      if (i === 0) time.value = item.createTime
      arr.push({
        msgType: MsgType.Notify,
        msg: { content: item.createTime },
        createTime: item.createTime,
        id: item.createTime
      })
      arr.push(...item.items)
    })
    // 追加到聊天消息列表
    list.value.unshift(...arr)
    // 没有数据则提示
    loading.value = false
    if (!data.length) {
      return new Toast('暂无聊天记录')
    }
    //第一次滚动到底部
    if (initialMsg.value) {
      await nextTick(() => {
        socket.emit('updateMsgStatus', arr[arr.length - 1].id) //消息已读
        window.scrollTo(0, document.body.scrollHeight)
        initialMsg.value = false
      })
    }
  })


  // 2.监听订单状态
  // 订单状态 在onMounted注册
  socket.on('statusChange', async () => {
    const res = await getConsultOrderDetail(route.query.orderId as string)
    consult.value = res.data
  })
  // 3.接收消息
  socket.on('receiveChatMsg', async (event) => {
    list.value.push(event)
    await nextTick()
    //消息已读
    socket.emit('updateMsgStatus', event.id) //消息已读
    window.scrollTo(0, document.body.scrollHeight)
  })
})

// 获取订单详情
const consult = ref<ConsultOrderItem>()
onMounted(async () => {
  const res = await getConsultOrderDetail(route.query.orderId as string)
  consult.value = res.data
})

const sendText = (text: string) => {
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgText,
    msg: { content: text }
  })
}
const sendImage = (data: { id: string, url: string }) => {
  // 发送信息需要  发送人  收消息人  消息类型  消息内容
  socket.emit('sendChatMsg', {
    from: store.user?.id,
    to: consult.value?.docInfo?.id,
    msgType: MsgType.MsgImage,
    msg: {
      picture: data
    }
  })
}
// 下来刷新
const time = ref(dayjs().format('YYYY-MM-DD HH:mm:ss'))
const loading = ref(false)
const onRefresh = () => {
  socket.emit('getChatMsgList', 20, time.value, route.query.orderId)
}

</script>
<template>
  <div class="room-page">
    <cp-nav-bar title="医生问诊室"></cp-nav-bar>
    <room-status :status="consult?.status" :countdown="consult?.countdown" />
    <van-pull-refresh v-model="loading" @refresh="onRefresh">
      <room-list :list="list" />
    </van-pull-refresh>
    <room-action :disabled="consult?.status !== OrderType.ConsultChat" @send-text="sendText" @send-image="sendImage" />
  </div>
</template>
<style lang="scss" scoped>
.room-page {
  padding-top: 90px;
  padding-bottom: 60px;
  min-height: 100vh;
  box-sizing: border-box;
  background-color: var(--cp-bg);

  .van-pull-refresh {
    width: 100%;
    min-height: calc(100vh - 150px);
  }
}
</style>